<template>
  <view class="parking-center">
    <!-- 权限检查提示 -->
    <view v-if="!hasManagementPermission" class="permission-notice">
      <u-notice-bar 
        text="您当前为普通用户，只能查看停车场信息，如需管理功能请联系管理员获取物业公司权限"
        type="warning"
        :show-icon="true"
      />
    </view>

    <!-- 顶部搜索区域 -->
    <view class="search-section">
      <u-search
        v-model="searchKeyword"
        placeholder="搜索停车场"
        :show-action="true"
        action-text="搜索"
        @search="handleSearch"
        @custom="handleSearch"
      />
    </view>

    <!-- 快捷功能区域 -->
    <view class="quick-actions">
      <view class="action-item" @click="handleMyVehicles">
        <u-icon name="car" size="24" color="#409EFF"></u-icon>
        <text class="action-text">我的车辆</text>
      </view>
      <view class="action-item" @click="handleParkingRecord">
        <u-icon name="list" size="24" color="#67C23A"></u-icon>
        <text class="action-text">停车记录</text>
      </view>
      <view class="action-item" @click="handleChargingStation">
        <u-icon name="battery" size="24" color="#E6A23C"></u-icon>
        <text class="action-text">充电桩</text>
      </view>
      <view class="action-item" @click="handleParkingFee">
        <u-icon name="rmb-circle" size="24" color="#F56C6C"></u-icon>
        <text class="action-text">停车费</text>
      </view>
      <!-- 管理功能 - 仅物业公司人员可见 -->
      <view v-if="hasManagementPermission" class="action-item" @click="handleManagement">
        <u-icon name="setting" size="24" color="#909399"></u-icon>
        <text class="action-text">管理功能</text>
      </view>
    </view>

    <!-- 附近停车场 -->
    <view class="nearby-section">
      <view class="section-header">
        <text class="section-title">附近停车场</text>
        <text class="section-more" @click="handleViewMore">查看更多</text>
      </view>
      
      <view class="parking-list">
        <view 
          class="parking-item" 
          v-for="item in parkingList" 
          :key="item.id"
          @click="handleSelectParking(item)"
        >
          <view class="parking-info">
            <view class="parking-name">{{ item.lotName }}</view>
            <view class="parking-address">{{ item.address }}</view>
            <view class="parking-status">
              <text class="status-text">空闲车位：{{ item.availableSpaces }}/{{ item.totalSpaces }}</text>
              <text class="occupancy-rate">占用率：{{ item.occupancyRate }}%</text>
            </view>
            <view class="parking-price">
              <text class="price-text">停车费：{{ item.pricePerHour }}元/小时</text>
            </view>
          </view>
          <view class="parking-actions">
            <u-button 
              size="mini" 
              type="primary" 
              @click.stop="handleNavigate(item)"
            >
              导航
            </u-button>
            <u-button 
              size="mini" 
              type="success" 
              @click.stop="handleViewDetail(item)"
            >
              详情
            </u-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 推荐停车场 -->
    <view class="recommend-section" v-if="recommendList.length > 0">
      <view class="section-header">
        <text class="section-title">推荐停车场</text>
      </view>
      
      <view class="recommend-list">
        <view 
          class="recommend-item" 
          v-for="item in recommendList" 
          :key="item.id"
          @click="handleSelectParking(item)"
        >
          <view class="recommend-info">
            <view class="recommend-name">{{ item.lotName }}</view>
            <view class="recommend-desc">{{ item.description }}</view>
            <view class="recommend-tags">
              <u-tag 
                v-for="tag in item.tags" 
                :key="tag"
                :text="tag"
                size="mini"
                type="warning"
              />
            </view>
          </view>
          <view class="recommend-actions">
            <u-button 
              size="mini" 
              type="primary" 
              @click.stop="handleNavigate(item)"
            >
              导航
            </u-button>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部工具栏 -->
    <view class="bottom-toolbar">
      <view class="toolbar-item" @click="handleRefresh">
        <u-icon name="reload" size="20"></u-icon>
        <text class="toolbar-text">刷新</text>
      </view>
      <view class="toolbar-item" @click="handleLocation">
        <u-icon name="map-pin" size="20"></u-icon>
        <text class="toolbar-text">定位</text>
      </view>
      <view class="toolbar-item" @click="handleFilter">
        <u-icon name="filter" size="20"></u-icon>
        <text class="toolbar-text">筛选</text>
      </view>
      <view class="toolbar-item" @click="handleSettings">
        <u-icon name="setting" size="20"></u-icon>
        <text class="toolbar-text">设置</text>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <u-popup v-model="filterVisible" mode="bottom" border-radius="16">
      <view class="filter-popup">
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <u-icon name="close" @click="filterVisible = false"></u-icon>
        </view>
        
        <view class="filter-content">
          <view class="filter-item">
            <text class="filter-label">距离范围</text>
            <u-slider 
              v-model="filterForm.distance" 
              :min="1" 
              :max="10" 
              :step="1"
              show-value
            />
          </view>
          
          <view class="filter-item">
            <text class="filter-label">价格范围</text>
            <u-slider 
              v-model="filterForm.price" 
              :min="0" 
              :max="20" 
              :step="1"
              show-value
            />
          </view>
          
          <view class="filter-item">
            <text class="filter-label">车位类型</text>
            <u-checkbox-group v-model="filterForm.spaceTypes">
              <u-checkbox 
                v-for="type in spaceTypeOptions" 
                :key="type.value"
                :name="type.value"
                :label="type.label"
              />
            </u-checkbox-group>
          </view>
          
          <view class="filter-item">
            <text class="filter-label">充电桩</text>
            <u-switch v-model="filterForm.hasCharging" />
          </view>
        </view>
        
        <view class="filter-footer">
          <u-button @click="handleFilterReset">重置</u-button>
          <u-button type="primary" @click="handleFilterConfirm">确定</u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onShow, computed } from 'vue'
import { parkingLotAPI } from '@/api/parking'
import { useUserStore } from '@/store'
import { isSuperAdmin, isPropertyCompanyUser } from '@/utils/permission'

// 作者：Wu.Liang

// 用户状态
const userStore = useUserStore()

// 权限检查
const hasManagementPermission = computed(() => {
  return isSuperAdmin() || isPropertyCompanyUser()
})

// 响应式数据
const searchKeyword = ref('')
const parkingList = ref([])
const recommendList = ref([])
const filterVisible = ref(false)
const loading = ref(false)

// 筛选表单
const filterForm = reactive({
  distance: 5,
  price: 10,
  spaceTypes: [],
  hasCharging: false
})

// 车位类型选项
const spaceTypeOptions = [
  { label: '普通车位', value: 1 },
  { label: '充电车位', value: 2 },
  { label: '残疾人车位', value: 3 }
]

// 生命周期
onMounted(() => {
  loadParkingData()
})

onShow(() => {
  // 页面显示时刷新数据
  loadParkingData()
})

// 方法定义
const loadParkingData = async () => {
  loading.value = true
  try {
    // 获取附近停车场
    const nearbyResponse = await parkingLotAPI.getNearby({
      latitude: getCurrentLocation().latitude,
      longitude: getCurrentLocation().longitude,
      radius: filterForm.distance * 1000
    })
    parkingList.value = nearbyResponse.data

    // 获取推荐停车场
    const recommendResponse = await parkingLotAPI.getRecommend()
    recommendList.value = recommendResponse.data
  } catch (error) {
    console.error('加载停车场数据失败:', error)
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    loadParkingData()
    return
  }
  
  try {
    const response = await parkingLotAPI.search({
      keyword: searchKeyword.value,
      ...filterForm
    })
    parkingList.value = response.data
  } catch (error) {
    console.error('搜索停车场失败:', error)
    uni.showToast({
      title: '搜索失败',
      icon: 'none'
    })
  }
}

const handleSelectParking = (item) => {
  uni.navigateTo({
    url: `/pages/parking/detail?id=${item.id}`
  })
}

const handleNavigate = (item) => {
  uni.openLocation({
    latitude: item.latitude,
    longitude: item.longitude,
    name: item.lotName,
    address: item.address
  })
}

const handleViewDetail = (item) => {
  uni.navigateTo({
    url: `/pages/parking/detail?id=${item.id}`
  })
}

const handleViewMore = () => {
  uni.navigateTo({
    url: '/pages/parking/list'
  })
}

const handleMyVehicles = () => {
  uni.navigateTo({
    url: '/pages/parking/vehicle'
  })
}

const handleParkingRecord = () => {
  uni.navigateTo({
    url: '/pages/parking/record'
  })
}

const handleChargingStation = () => {
  uni.navigateTo({
    url: '/pages/parking/charging'
  })
}

const handleParkingFee = () => {
  uni.navigateTo({
    url: '/pages/parking/fee'
  })
}

const handleManagement = () => {
  uni.navigateTo({
    url: '/pages/parking/management'
  })
}

const handleRefresh = () => {
  loadParkingData()
  uni.showToast({
    title: '刷新成功',
    icon: 'success'
  })
}

const handleLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      console.log('当前位置:', res)
      loadParkingData()
    },
    fail: () => {
      uni.showToast({
        title: '获取位置失败',
        icon: 'none'
      })
    }
  })
}

const handleFilter = () => {
  filterVisible.value = true
}

const handleSettings = () => {
  uni.navigateTo({
    url: '/pages/parking/settings'
  })
}

const handleFilterReset = () => {
  Object.assign(filterForm, {
    distance: 5,
    price: 10,
    spaceTypes: [],
    hasCharging: false
  })
}

const handleFilterConfirm = () => {
  filterVisible.value = false
  loadParkingData()
}

const getCurrentLocation = () => {
  // 这里应该从缓存或全局状态获取当前位置
  // 暂时返回默认位置
  return {
    latitude: 39.9042,
    longitude: 116.4074
  }
}
</script>

<style scoped>
.parking-center {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

.search-section {
  background-color: #fff;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.quick-actions {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 30rpx 20rpx;
  margin-bottom: 20rpx;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
}

.action-text {
  font-size: 24rpx;
  color: #666;
}

.nearby-section,
.recommend-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.section-more {
  font-size: 28rpx;
  color: #409EFF;
}

.parking-list,
.recommend-list {
  padding: 0 20rpx;
}

.parking-item,
.recommend-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #eee;
}

.parking-item:last-child,
.recommend-item:last-child {
  border-bottom: none;
}

.parking-info,
.recommend-info {
  flex: 1;
  margin-right: 20rpx;
}

.parking-name,
.recommend-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.parking-address,
.recommend-desc {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.parking-status {
  display: flex;
  gap: 20rpx;
  margin-bottom: 10rpx;
}

.status-text,
.occupancy-rate {
  font-size: 24rpx;
  color: #999;
}

.parking-price {
  margin-bottom: 10rpx;
}

.price-text {
  font-size: 26rpx;
  color: #f56c6c;
}

.recommend-tags {
  display: flex;
  gap: 10rpx;
  margin-bottom: 10rpx;
}

.parking-actions,
.recommend-actions {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.bottom-toolbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 20rpx;
  border-top: 1rpx solid #eee;
}

.toolbar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.toolbar-text {
  font-size: 24rpx;
  color: #666;
}

.filter-popup {
  background-color: #fff;
  border-radius: 32rpx 32rpx 0 0;
  padding: 40rpx;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
}

.filter-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.filter-content {
  margin-bottom: 40rpx;
}

.filter-item {
  margin-bottom: 40rpx;
}

.filter-label {
  display: block;
  font-size: 30rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.filter-footer {
  display: flex;
  gap: 20rpx;
}
</style> 